<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <script>
    // const nextTick = function () {
    //   const callbacks = [];
    //   let pending = false;
    //   const p = Promise.resolve;

    //   //   安排异步任务执行回调队列
    //   const flushCallbacks = () => {
    //     pending = false;
    //     const pendingCallBacks = callbacks.slice(0);
    //     callbacks.length = 0;
    //     for (const cb of pendingCallBacks) {
    //       try {
    //         cb();
    //       } catch (error) {
    //         console.error(error);
    //       }
    //     }
    //   };

    //   const asyncTack = () => {
    //     p().then(flushCallbacks());
    //     // 为了确保只在浏览器环境中添加宏任务兜底，保持跨环境兼容
    //     // 如果不检查在node.js中执行setTimeout会报错
    //     // 宏任务兜底是为了即使微任务堵塞,宏任务也会在未来某个时间点执行
    //     if (typeof window !== 'undefined') {
    //       setTimeout(() => {}, 0);
    //     }
    //   };
    //   // 确保只安排一个异步任务
    //   const ensureCallback = () => {
    //     if (!pending) {
    //       pending = true;
    //       asyncTack();
    //     }
    //   };

    //   return function (fn) {
    //     callbacks.push(fn);
    //     ensureCallback();
    //   };
    // };

    function nextTick() {
      const callbacks = [];
      let pending = false;

      const flushCallbacks = () => {
        pending = false;
        const pendingCallbacks = callbacks.slice(0);
        callbacks.length = 0;

        for (const cb of pendingCallbacks) {
          try {
            cb();
          } catch (error) {
            console.error(error);
          }
        }
      };

      const asyncTask = () => {
        Promise.resolve().then(flushCallbacks);
        if (typeof window !== 'undefined') {
          setTimeout(() => {}, 0);
        }
      };

      const ensureCallbacks = () => {
        if (!pending) {
          pending = true;
          asyncTask();
        }
      };

      return function (fn) {
        callbacks.push(fn);
        ensureCallbacks();
      };
    }

    // 创建 nextTick 实例
    const myNextTick = nextTick();

    // 使用 nextTick 延迟执行回调
    console.log('同步代码开始');

    myNextTick(() => {
      console.log('异步回调执行');
    });

    console.log('同步代码继续');

    // 输出顺序：
    // 同步代码开始
    // 同步代码继续
    // 异步回调执行
  </script>
  <body></body>
</html>
